//
//  BLEManager.h
//  BLESDK
//
//  Created on Desktop.
//

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>

NS_ASSUME_NONNULL_BEGIN

@class BLEManager;

// 连接状态
typedef NS_ENUM(NSInteger, BLEConnectionState) {
    BLEConnectionStateDisconnected = 0,
    BLEConnectionStateConnecting,
    BLEConnectionStateConnected,
    BLEConnectionStateDisconnecting
};

// 扫描过滤选项
typedef NS_OPTIONS(NSUInteger, BLEScanFilter) {
    BLEScanFilterNone         = 0,
    BLEScanFilterName         = 1 << 0,  // 按名称过滤
    BLEScanFilterServices     = 1 << 1,  // 按服务过滤
    BLEScanFilterRSSI         = 1 << 2,  // 按信号强度过滤
};

/**
 * BLE状态回调代理
 */
@protocol BLEManagerDelegate <NSObject>

@optional
/**
 * 蓝牙状态改变回调
 */
- (void)bleManager:(BLEManager *)manager didUpdateState:(CBManagerState)state;

/**
 * 发现周边设备回调
 */
- (void)bleManager:(BLEManager *)manager didDiscoverPeripheral:(CBPeripheral *)peripheral
    advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;

/**
 * 连接状态改变回调
 */
- (void)bleManager:(BLEManager *)manager didUpdateConnectionState:(BLEConnectionState)state forPeripheral:(CBPeripheral *)peripheral;

/**
 * 连接成功回调
 */
- (void)bleManager:(BLEManager *)manager didConnectPeripheral:(CBPeripheral *)peripheral;

/**
 * 连接失败回调
 */
- (void)bleManager:(BLEManager *)manager didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;

/**
 * 断开连接回调
 */
- (void)bleManager:(BLEManager *)manager didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;

/**
 * 发现服务回调
 */
- (void)bleManager:(BLEManager *)manager didDiscoverServices:(NSArray<CBService *> *)services forPeripheral:(CBPeripheral *)peripheral;

/**
 * 发现特征值回调
 */
- (void)bleManager:(BLEManager *)manager didDiscoverCharacteristics:(NSArray<CBCharacteristic *> *)characteristics forService:(CBService *)service peripheral:(CBPeripheral *)peripheral;

/**
 * 收到数据回调
 */
- (void)bleManager:(BLEManager *)manager didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic peripheral:(CBPeripheral *)peripheral;

/**
 * 写入数据完成回调
 */
- (void)bleManager:(BLEManager *)manager didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;

/**
 * 通知状态改变回调
 */
- (void)bleManager:(BLEManager *)manager didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic enabled:(BOOL)enabled error:(nullable NSError *)error;

@end

/**
 * 低功耗蓝牙管理器
 */
@interface BLEManager : NSObject

/** 代理 */
@property (nonatomic, weak) id<BLEManagerDelegate> delegate;

/** 当前连接的设备 */
@property (nonatomic, strong, readonly) CBPeripheral *connectedPeripheral;

/** 当前连接状态 */
@property (nonatomic, assign, readonly) BLEConnectionState connectionState;

/** 蓝牙是否开启 */
@property (nonatomic, assign, readonly) BOOL isBluetoothEnabled;

/** 自动重连次数，设为0则不自动重连 */
@property (nonatomic, assign) NSUInteger autoReconnectCount;

/** 扫描超时时间（秒） */
@property (nonatomic, assign) NSTimeInterval scanDuration;

/** 连接超时时间（秒） */
@property (nonatomic, assign) NSTimeInterval connectionTimeout;

/** 是否正在扫描中 */
@property (nonatomic, assign, readonly) BOOL isScanning;

/** 单例方法 */
+ (instancetype)sharedInstance;

/**
 * 应用SDK选项
 * @param options 选项字典
 */
- (void)applyOptions:(NSDictionary *)options;

/** 
 * 开始扫描设备 
 * @param serviceUUIDs 要扫描的服务UUID数组，传nil表示扫描所有设备
 */
- (void)startScanWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs;

/**
 * 开始扫描设备（带过滤选项）
 * @param serviceUUIDs 要扫描的服务UUID数组
 * @param namePrefix 设备名称前缀，符合前缀的设备会被过滤出来
 * @param rssiThreshold RSSI阈值，信号强度大于此值的设备会被过滤出来
 * @param filter 过滤选项
 */
- (void)startScanWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs 
                   namePrefix:(nullable NSString *)namePrefix 
                rssiThreshold:(NSInteger)rssiThreshold 
                       filter:(BLEScanFilter)filter;

/** 停止扫描设备 */
- (void)stopScan;

/**
 * 连接设备
 * @param peripheral 要连接的设备
 */
- (void)connectPeripheral:(CBPeripheral *)peripheral;

/**
 * 连接设备（带超时）
 * @param peripheral 要连接的设备
 * @param timeout 连接超时时间
 * @param completion 连接完成回调
 */
- (void)connectPeripheral:(CBPeripheral *)peripheral 
                  timeout:(NSTimeInterval)timeout 
               completion:(nullable void(^)(BOOL success, NSError * _Nullable error))completion;

/**
 * 断开当前连接
 */
- (void)disconnect;

/**
 * 发送数据
 * @param data 要发送的数据
 * @param characteristic 特征值
 * @return 是否发送成功
 */
- (BOOL)writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic;

/**
 * 读取特征值数据
 * @param characteristic 特征值
 */
- (void)readValueForCharacteristic:(CBCharacteristic *)characteristic;

/**
 * 订阅特征值通知
 * @param enabled 是否启用通知
 * @param characteristic 特征值
 */
- (void)setNotifyValue:(BOOL)enabled forCharacteristic:(CBCharacteristic *)characteristic;

/**
 * 获取已扫描到的所有设备列表
 * @return 设备数组
 */
- (NSArray<CBPeripheral *> *)discoveredPeripherals;

/**
 * 根据设备名称查找设备
 * @param name 设备名称
 * @return 找到的设备，未找到则返回nil
 */
- (nullable CBPeripheral *)peripheralWithName:(NSString *)name;

/**
 * 根据UUID查找设备
 * @param UUIDString UUID字符串
 * @return 找到的设备，未找到则返回nil
 */
- (nullable CBPeripheral *)peripheralWithUUIDString:(NSString *)UUIDString;

@end

NS_ASSUME_NONNULL_END 